﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';

class RingSettingLogic extends GetxController {
  final unitFormat = ''.obs; // 单位格式：公制/英制
  final temperatureUnit = ''.obs; // 温度单位
  final intervalTime = 0.obs; // 白天心率/HRV测量间隔（分钟）
  final oxygenSaturation = 0.obs; // 血氧饱和度（小时）
  final pressure = 0.obs; // 压力（小时）

  @override
  void onInit() {
    super.onInit();
    loadSettings();
  }

  /// 加载设置
  Future<void> loadSettings() async {
    try {
      final response = await DefaultApi().queryMyOtherSetGet(
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          unitFormat.value = data['unitFormat'] ?? '';
          temperatureUnit.value = data['temperatureUnit'] ?? '';
          intervalTime.value = data['intervalTime'] ?? 0;
          oxygenSaturation.value = data['oxygenSaturation'] ?? 0;
          pressure.value = data['pressure'] ?? 0;
        }
      }
    } catch (e) {
      print('加载戒指设置失败: $e');
    }
  }

  /// 更新设置
  Future<void> updateSettings() async {
    try {
      final response = await DefaultApi().operationMyOtherSetPost(
        unitFormat: unitFormat.value.isNotEmpty ? unitFormat.value : null,
        temperatureUnit: temperatureUnit.value.isNotEmpty ? temperatureUnit.value : null,
        intervalTime: intervalTime.value > 0 ? intervalTime.value : null,
        oxygenSaturation: oxygenSaturation.value > 0 ? oxygenSaturation.value : null,
        pressure: pressure.value > 0 ? pressure.value : null,
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        Toast.show('设置已更新');
      }
    } catch (e) {
      print('更新戒指设置失败: $e');
    }
  }

  /// 选择单位格式
  void selectUnitFormat() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Color(0xFF282528),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: const Text('公制', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () {
                  unitFormat.value = '公制';
                  Get.back();
                  updateSettings();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('英制', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () {
                  unitFormat.value = '英制';
                  Get.back();
                  updateSettings();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('取消', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () => Get.back(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择测量间隔
  void selectIntervalTime() {
    final intervals = [5, 10, 15, 20, 25, 30, 60];
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Color(0xFF282528),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ...intervals.map((interval) => Column(
                    children: [
                      ListTile(
                        title: Text('$interval分钟',
                            style: const TextStyle(color: Colors.white),
                            textAlign: TextAlign.center),
                        onTap: () {
                          intervalTime.value = interval;
                          Get.back();
                          updateSettings();
                        },
                      ),
                      if (interval != intervals.last)
                        const Divider(height: 1, color: Color(0xFF1A1A1A)),
                    ],
                  )),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('取消',
                    style: TextStyle(color: Colors.white),
                    textAlign: TextAlign.center),
                onTap: () => Get.back(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择血氧饱和度间隔
  void selectOxygenSaturation() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Color(0xFF282528),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: const Text('1小时', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () {
                  oxygenSaturation.value = 1;
                  Get.back();
                  updateSettings();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('2小时', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () {
                  oxygenSaturation.value = 2;
                  Get.back();
                  updateSettings();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('取消', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () => Get.back(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 选择压力间隔
  void selectPressure() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Color(0xFF282528),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: const Text('1小时', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () {
                  pressure.value = 1;
                  Get.back();
                  updateSettings();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('2小时', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () {
                  pressure.value = 2;
                  Get.back();
                  updateSettings();
                },
              ),
              const Divider(height: 1, color: Color(0xFF1A1A1A)),
              ListTile(
                title: const Text('取消', style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
                onTap: () => Get.back(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
